package com.guli.base.code.controller;//package com.guli.base.code.controller;


import com.jingxi.common.dto.R;
import com.jingxi.common.multi.ImageUtils;
import com.jingxi.common.rand.RandomUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

@RestController
@RequestMapping("/base/code")
public class CaptchaController {

    @GetMapping("/captcha")
    public R<String> getCaptcha() throws IOException {
        String codeStr = RandomUtils.generateCode(4);
        byte[] binary = ImageUtils.burstCaptcha(codeStr);
        byte[] encoded = new Base64().encode(binary);
        String base64Str = new String(encoded, "UTF-8");
        return R.ok("返回的是一个base64加密的二进制文件" + base64Str);
    }

    @GetMapping("/qr")
    public void getQr(HttpServletResponse httpServletResponse, HttpServletRequest request, @RequestParam("uuid") String uuid) throws IOException {
        ImageUtils.burstQr(uuid,httpServletResponse.getOutputStream());
    }

    @GetMapping("/qrCheck")
    public void qrCheck(HttpServletResponse httpServletResponse
            , @RequestParam("uuid") String uuid
            , @RequestParam("ok") Boolean bool
    ) throws IOException {
        if(bool){
            String html = """
                <html>
                    <head>
                        <title>登录响应</title>
                    </head>
                    <body>
                        <h1>设备(%s)成功登录!</h1>
                    </body>
                </html>
                """;
            html = String.format(html,uuid);
            httpServletResponse.setCharacterEncoding("utf-8");
            httpServletResponse.getOutputStream().write(html.getBytes());
            //调登录接口
            //前端sse感知登录成功后，跳转主页
        }
    }
}
